package com.se.xb.filter;

import com.se.xb.entity.User;
import com.se.xb.service.UserService;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebFilter(filterName = "AutoLoginFilter", urlPatterns = "/*")
public class AutoLoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化逻辑（如果有需要）
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 将 ServletRequest 转换为 HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        UserService userService = new UserService();

        // 获取会话
        HttpSession session = request.getSession(false); // 不创建新的会话
        if (session != null) {
            // 检查会话中是否有用户信息
            Object user = session.getAttribute("user");
            if (user == null) {
                // 会话中没有用户信息，尝试从 Cookie 中获取用户名
                Cookie[] cookies = request.getCookies();
                if (cookies != null) {
                    for (Cookie cookie : cookies) {
                        if ("username".equals(cookie.getName())) {
                            String username = cookie.getValue();
                            // 查询数据库获取用户信息
                            User userFromDB = null;
                            try {
                                userFromDB = userService.getUserByUsername(username);
                            } catch (SQLException e) {
                                throw new RuntimeException(e);
                            }
                            if (userFromDB != null) {
                                // 将用户信息存入会话
                                session.setAttribute("user", userFromDB);
                                break; // 找到用户名后退出循环
                            }
                        }
                    }
                }
            }
        }

        // 继续后续的过滤器链或目标资源
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 清理资源（如果有需要）
    }
}